package edu.scu.declaresys.dao.util;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;


public class FieldWalker
{
	public static String TAG = "FieldWalker";
	//
	//determine show which part.
	//
	public static int WITH_NULL = 1;
	public static int WITHOUT_NULL = 2;
	public static int ONLY_NULL = 1;
	
	//
	//util
	//
	public static String makeFieldString(boolean hasStatic, boolean hasNonstatic, Object obj, int flag)
	{
		StringBuffer sb = new StringBuffer();
		Field[] fields = obj.getClass().getDeclaredFields();
		Field.setAccessible(fields, true);
		sb.append("{");
		boolean isEmpty = true;
		for(Field field : fields)
		{
			Object v = null;
			if(Modifier.isStatic(field.getModifiers()))
			{
				if(!hasStatic)
				{
					continue;
				}
			}
			else
			{
				if(!hasNonstatic)
				{
					continue;
				}
			}
			
			try
			{
				v = field.get(obj);
			}
			catch(IllegalArgumentException e)
			{
				return null;
			}
			catch (IllegalAccessException e)
			{
				return null;
			}
			if(flag == WITH_NULL)
			{
				sb.append(field.getName()).append(" = ").append(v).append(", ");
				isEmpty = false;
			}
			else if(flag == WITHOUT_NULL)
			{
				if(v != null)
				{
					sb.append(field.getName()).append(" = ").append(v).append(", ");
					isEmpty = false;
				}				
			}
			else if(flag == ONLY_NULL)
			{
				if(v == null)
				{
					sb.append(field.getName()).append(" = ").append(v).append(", ");
					isEmpty = false;
				}
			}
		}
		if(!isEmpty)
		{
			sb.delete(sb.length() - 2, sb.length());
		}		
		sb.append("}");
		return sb.toString();
	}
	
	public static String makeNonstaticFields(Object obj, int flag)
	{
		return makeFieldString(false, true, obj, flag);
	}
	
	public static String makeStaticFields(Object obj, int flag)
	{
		return makeFieldString(true, false, obj, flag);
	}
	
	public static String makeAllFields(Object obj, int flag)
	{
		return makeFieldString(true, true, obj, flag);
	}
}
